package serie09;

import java.util.Observable;

public class StdSpeedometerModel extends Observable 
												implements SpeedometerModel {

	// ATTRIBUTS 
	
	// La vitesse limite
	private double maxSpeed;
	
	// La vitesse instantanée
	private double speed;
	
	// Le pas de modification de la vitesse
	private double step;
	
	// L'unité de vitesse courante
	private SpeedUnit unit;
	
	// Indique si le contact est mis ou pas
	private boolean on;
	
	// CONSTRUCTEURS
	
	public StdSpeedometerModel(double step, double max) {
		if (step < 1 || step > max) {
			throw new IllegalArgumentException(
					"Pas incompatible avec la vitesse maximale"
			);
		}
		speed = 0;
		maxSpeed = max;
		unit = SpeedUnit.KMH;
		on = false;
		this.step = step;
		setChanged();
	}
	
	// REQUETES
    
    public double getMaxSpeed() {
    	return maxSpeed;
    }
    
    public double getSpeed() {
    	return speed;
    }
   
    public double getStep() {
    	return step;
    }
    
    public SpeedUnit getUnit() {
    	return unit;
    }
    
    public boolean isOn() {
    	return on;
    }
    
    // COMMANDES
    
    public void setUnit(SpeedUnit unit) {
    	if (unit == null) {
    		throw new IllegalArgumentException("Vitesse non r�f�renc�e");
    	}
    	
    	this.speed = speed * unit.getUnitPerKm() / this.unit.getUnitPerKm();
    	this.step = step * unit.getUnitPerKm() / this.unit.getUnitPerKm();
    	this.maxSpeed = maxSpeed * unit.getUnitPerKm() 
    					/ this.unit.getUnitPerKm();
    	this.unit = unit;
    	setChanged();
        notifyObservers();
    }
    
    public void slowDown() {
    	if (!isOn()) {
    		throw new IllegalStateException("Contact pas allum�");
    	}
    	speed = Math.max(0, getSpeed() - getStep());
    	setChanged();
        notifyObservers();
    }
   
    public void speedUp() {
    	if (!isOn()) {
    		throw new IllegalStateException("Contact pas allum�");
    	}
    	speed = Math.min(getMaxSpeed(), getSpeed() + getStep());
    	setChanged();
        notifyObservers();
    }
    
    public void turnOff() {
    	if (!isOn()) {
    		throw new IllegalStateException("Contact d�j� �teint");
    	}
    	on = false;
    	speed = 0;
    	setChanged();
        notifyObservers();
    }
   
    public void turnOn() {
    	if (isOn()) {
    		throw new IllegalStateException("Contact d�j� mis");
    	}
    	on = true;
    	setChanged();
        notifyObservers();
    }
}
